<template>
  <a-card title="节点信息" size="small" class="property-panel" ref="propertyPanel">
    <a-form :form="form" :labalCol="{span:2}" size="small">
      <a-form-item class="itemm" label="节点ID" :hidden="true">
        <a-input v-model="form.id" disabled></a-input>
      </a-form-item>
      <a-form-item class="itemm" label="节点名称">
        <a-input v-model="form.name" @change="nameChange" disabled></a-input>
      </a-form-item>
      <!-- <a-form-item label="节点颜色">
        <a-color-picker v-model="form.color" @change="colorChange"></a-color-picker>
      </a-form-item>-->
      <!-- 任务节点允许选择人员 -->
      <a-form-item  class="itemm" label="节点人员" v-if="userTask">
        <a-select v-model="form.userType" placeholder="请选择" @change="typeChange" :disabled="true">
          <a-select-option value="assignee">指定人员</a-select-option>
          <a-select-option value="candidateUsers">团队人员</a-select-option>
          <a-select-option value="candidateGroups">团队角色</a-select-option>
        </a-select>
      </a-form-item>

      <!--
            &lt;!&ndash;指定人员里区分的指定区域&ndash;&gt;
            <a-form-item label="指定区域" v-if="userTask && form.userType === 'assignee'">
              <a-select v-model="form.type" placeholder="请选择">
                <a-select-option value="1">指定人员</a-select-option>
                <a-select-option value="2">团队人员</a-select-option>
              </a-select>
            </a-form-item>-->


      <!-- 指定人员 -->
      <a-form-item  class="itemm" label="指定人员" v-if="userTask && form.userType === 'assignee'">
        <a-select
          v-model="form.assignee"
          placeholder="请选择"
          key="1"
          optionFilterProp="children"
          :showSearch="true"
          @change="(value) => addUser({assignee: value})"
          :disabled="true"
        >
          <a-select-option v-for="item in users"  :key="item.id" :value="item.id">{{item.realname}}</a-select-option>
        </a-select>
      </a-form-item>
      <!-- &lt;!&ndash; 候选人员 &ndash;&gt;
       <a-form-item label="候选人员" v-else-if="userTask && form.userType === 'candidateUsers'">
         <a-select
           v-model="form.candidateUsers"
           placeholder="请选择"
           key="2"
           mode="multiple"
           optionFilterProp="children"
           :showSearch="true"
           @change="(value) => addUser({candidateUsers: value.join(',') || value})"
         >
           <a-select-option v-for="item in users" :key="item.id" :value="item.id">{{item.username}}</a-select-option>
         </a-select>
       </a-form-item>-->
      <!-- 角色/岗位 -->
      <a-form-item  class="itemm" label="团队角色" v-else-if="userTask && form.userType === 'candidateGroups'">
        <a-select
          v-model="form.candidateGroups"
          placeholder="请选择"
          key="2"
          optionFilterProp="children"
          :showSearch="true"
          @change="(value) => addUser({candidateGroups: value})"
          :disabled="true"
        >
          <a-select-option v-for="item in roles" :key="item.id"  :value="item.id">{{item.teamRolename}}</a-select-option>
        </a-select>
      </a-form-item>

      <!-- 团队名称-->
      <a-form-item  class="itemm" label="团队名称" v-else-if="userTask && form.userType === 'candidateUsers'">
        <a-select
          v-model="form.teams"
          placeholder="请选择"
          key="3"
          optionFilterProp="children"
          :showSearch="true"
          @change="(value) => updateTeams({teams: value})"
        >
          <a-select-option v-for="item in teams" :key="item.id" :disabled="true" :value="item.id">{{item.teamName}}</a-select-option>
        </a-select>
      </a-form-item>

      <!-- 团队名成员-->
      <a-form-item  class="itemm" label="团队成员" v-if="userTask && form.userType === 'candidateUsers'">
        <a-select v-model="form.candidateUsers" placeholder="请选择"
                  optionFilterProp="children"
                  key="4"
                  mode="multiple"
                  :showSearch="true"
                  @change="(value) => updateTeamPlayers({candidateUsers: value.join(',') || value})"
                  :disabled="true"
        >
          <a-select-option v-for="item in teamPlayers" :key="item.id" :value="item.username">{{item.username}}
          </a-select-option>
        </a-select>
      </a-form-item>


      <!-- 定义输入输入格式-->
      <!--    <a-form-item label="输入格式" v-if="userTask" v-show="false">
            <a-select
              placeholder="请选择"
              key="2"
              mode="multiple"
              v-model="form.inputFormat"
              @change="(value) => addInputFormat({inputFormat: value.join(',') || value})"
            >
              <a-select-option v-for="item in fileFormat" :key="item" :value="item">{{item}}
              </a-select-option>
            </a-select>
          </a-form-item>

          &lt;!&ndash; 定义输入输出格式&ndash;&gt;
          <a-form-item label="输出格式" v-if="userTask" v-show="false">
            <a-select
              placeholder="请选择"
              key="2"
              mode="multiple"
              v-model="form.outputFormat"
              @change="(value) => addOutputFormat({outputFormat: value.join(',') || value})"
            >
              <a-select-option v-for="item in fileFormat" :key="item" :value="item">{{item}}
              </a-select-option>
            </a-select>
          </a-form-item>-->
      <!--     &lt;!&ndash;添加任务节点开始时间和结束时间&ndash;&gt;-->
      <a-form-item class="itemm" label="计划开始时间" v-if="userTask">
        <a-date-picker
          placeholder="计划开始时间"
          v-model='form.taskStartTime'
          @change="(value) => startChange({taskStartTime: this.moment(value).format(this.dateFormat)})"
          type="date"
          :format="dateFormat"
          :disabled="true"
        />
      </a-form-item>
      <a-form-item class="itemm" label="计划结束时间" v-if="userTask">
        <a-date-picker
          :disabled="true"
          placeholder="计划结束时间"
          v-model='form.taskEndTime'
          @change="(value) => endChange({taskEndTime:  this.moment(value).format(this.dateFormat)})"
          type="date"
          :format="dateFormat"
          :disabledDate="disabledDateHandler"
        />
      </a-form-item>

      <a-form-item class="itemm" label="计划执行天数"  prop="totalTime" v-if="userTask">
        <a-input v-model="form.dateDiff"  placeholder="计划执行天数" :disabled="true"></a-input>
      </a-form-item>


      <!-- 分支允许添加条件 -->
      <a-form-item label="分支条件" v-if="sequenceFlow">
        <a-select v-model="form.user" placeholder="请选择" :disabled="true">
          <a-select-option v-for="item in users" :key="item.id" :title="item.id">{{item.username}}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
  import {getUserList} from '@/api/api'
  import {teamall, getTeamList, getRolenameList} from '@/api/team'
  import moment from 'moment'

  export default {
    name: 'PropertyPanel',
    props: {
      modeler: {
        type: Object,
        required: true
      },
      value: {
        type: String,
        required: false
      },
      dateFormat: {
        type: String,
        default: 'YYYY-MM-DD',
        required: false
      },
      triggerChange: {
        type: Boolean,
        required: false,
        default: false
      },
      readOnly: {
        type: Boolean,
        required: false,
        default: false
      },
      showTime: {
        type: Boolean,
        required: false,
        default: false
      },
      getCalendarContainer: {
        type: Function,
        default: () => document.body
      }

    },
    computed: {
      userTask() {
        if (!this.element) {
          return
        }
        return this.element.type === 'bpmn:UserTask'
      },
      sequenceFlow() {
        if (!this.element) {
          return
        }
        return this.element.type === 'bpmn:SequenceFlow'
      }
    },
    data() {
      let dateStr = this.value;
      return {
        decorator: "",
        form: this.$form.createForm(this),
        model: {
          id: '',
          name: '',
          color: null
        },
        element: {},
        users: [],   //用户列表的数据
        roles: [],  //团队角色行列的数据
        teams: [],   //团队名称的数据
        teamPlayers: [],    //团队成员遍历团队名称，根据名称来显示此团队的成员
        fileFormat: ['.dll', '.txt', '.xlsx', '.docx', '.rar'],
        activityId: "",
        totalTime: '',
        inputFileTypeArray: [],
        outputFileTypeArray: [],
        startTime: null,
        endTime: null,
        dateDiff: '',
        startArray: [],
        endArray: [],
        dateDiffArray: [],
      }
    },
    mounted() {
      this.loadRoles()
      this.loadUsers()
      this.handleModeler()
      this.loadTeams()
    },
    methods: {
      clearFields() {
        this.startTime = ""
        this.endTime = ""
        this.form.resetFields()
      },
      initData() {
        this.loadRoles()
        this.loadUsers()
        this.loadTeams()
      },
      loadUsers() {
        const vm = this
        getUserList().then(res => {
          vm.users = [].concat(res.result.records)
        })
      },
      loadRoles() {
        const vm = this
        getRolenameList().then(res => {
          vm.roles = [].concat(res.result.records)
        })
      },
      loadTeams() {
        const vm = this
        getTeamList().then(res => {
          vm.teams = [].concat(res.result.records)

        })
      },
      handleModeler() {
        // 监听节点选择变化
        this.modeler.on('selection.changed', this.selectionChanged)

        //  监听节点属性变化
        this.modeler.on('element.changed', this.elementChanged)
      },
      selectionChanged(e) {
        const element = e.newSelection[0]
        this.element = element
        if (!element) return
        this.form = {
          ...element.businessObject,
          ...element.businessObject.$attrs
        }
        if (this.form.userType === 'candidateUsers') {
          this.form['candidateUsers'] = this.form['candidateUsers'].split(',') || []
        }
        if (this.form.outputFormat != null) {
          this.form['outputFormat'] = this.form['outputFormat'].split(',') || []
        }
        if (this.form.taskStartTime != null) {
          let taskStartTime = this.form.taskStartTime;
          this.form.taskStartTime =this.moment(taskStartTime);
          console.log(taskStartTime)
        }
        if (this.form.taskEndTime != null) {
          let taskEndTime = this.form.taskEndTime;
          this.form.taskEndTime =this.moment(taskEndTime);
          console.log(taskEndTime)
        }
      },
      elementChanged(e) {
        const {element} = e
        this.activityId = element.id
        if (!element) return
        //  新增节点需要更新回属性面板
        if (element.id === this.form.id) {
          this.form.name = element.businessObject.name
          this.form = {...this.form}
        }

      },
      // 属性面板名称，更新回流程节点
      nameChange(e) {
        // let name = e.target.value
        let name = this.form.name
        const modeling = this.modeler.get("modeling");
        modeling.updateLabel(this.element, name);
      },

      //根据团队名称添加团队成员
      updateTeams(properties) {
        let that = this;
        /*     delete this.form.candidateUsers*/
        this.teams.forEach(function (item) {
          if (item.id == properties.teams) {
            console.log("++++++++++++++" + item.teamName);   //输出的是团队名称
            console.log("++++++++++++++item:" + item);   //输出的是团队名称
            that.teamPlayers = item.teamPlayerList;
            console.log("teamplayer:" + that.teamPlayers)
          }
        })
        /*    this.updateProperties(Object.assign({candidateGroups: properties.candidateGroups.teamName}, {
              userType: "candidateGroups"
            }))*/
        this.updateProperties(
          Object.assign(properties, {
            userType: Object.keys(properties)[0]
          })
        )
      },
      updateTeamPlayers(properties) {
        this.updateProperties(
          Object.assign(properties, {
            userType: Object.keys(properties)[0]
          })
        )
      },
      // 任务节点配置人员
      addUser(properties) {
        this.updateProperties(
          Object.assign(properties, {
            userType: Object.keys(properties)[0]
          })
        )
      },
      // 切换人员类型
      typeChange() {
        const types = ['assignee', 'candidateUsers', 'candidateGroups']
        types.forEach(type => {
          delete this.element.businessObject.$attrs[type]
          delete this.form[type]
        })
      },
      // 在这里我们封装一个通用的更新节点属性的方法
      updateProperties(properties) {
        const modeling = this.modeler.get('modeling')
        modeling.updateProperties(this.element, properties)
      },
      // 更新时间描述
      moment,
      startChange(properties) {
        let that = this
        this.updateProperties(properties)
        // let value = this.moment(properties.taskStartTime).format(this.dateFormat);
        // let index = this.startArray.findIndex(item => {
        //   return item.activityId == this.activityId
        // })
        // if (index == -1) {
        //   this.startArray.push({
        //     startTime: value,
        //     activityId: this.activityId
        //   })
        // } else {
        //   this.startArray[index].startTime = value
        // }
        // this.$emit('startType', this.startArray);
      },
      disabledDateHandler(date) {
        return date && date < moment(this.form.taskStartTime).endOf('day')
      },
      endChange(properties) {
        let that = this
        that.updateProperties(properties)
        that.form.dateDiff= that.moment(that.form.taskEndTime).diff(that.form.taskStartTime, "days");
        that.updateProperties({"dateDiff":that.form.dateDiff});
        console.log(dateDiff)
      }
      //   let index = this.endArray.findIndex(item => {
      //     return item.activityId == this.activityId
      //   })
      //   if (index == -1) {
      //     this.endArray.push({
      //       endTime: value,
      //       activityId: this.activityId
      //     })
      //   } else {
      //     this.endArray[index].endTime = value
      //   }
      //   // this.$emit('endType', this.endArray);
      //
      //   this.dateDiff= this.form.taskEndTime.diff(this.from.taskStartTime, "days");
      //   let index2 = this.dateDiffArray.findIndex(item => {
      //     return item.activityId == this.activityId
      //   })
      //   if (index == -1) {
      //     this.dateDiffArray.push({
      //       dateDiff: this.dateDiff,
      //       activityId: this.activityId
      //     })
      //   } else {
      //     this.dateDiffArray[index].dateDiff = this.dateDiff
      //   }
      //   this.$emit('dateDiffType', this.dateDiffArray);
      // }

      /*      addInputFormat(properties) {
              let that = this
              this.updateProperties({})
              Object.assign(properties, {activityId: that.activityId})

              let index = 0
              let bool = false
              that.inputFileTypeArray.forEach((val, key) => {
                if (val.activityId === that.activityId) {
                  bool = true
                  index = key
                }
              })

              if (bool) {
                that.inputFileTypeArray.splice(index, 1, properties)
              } else {
                that.inputFileTypeArray.push(properties)
              }

              this.$emit('inputFileType', that.inputFileTypeArray)
            },*/
      /*    addOutputFormat(properties) {
            let that = this
            // this.updateProperties({})

            this.updateProperties(properties)

            Object.assign(properties, {activityId: that.activityId})

            let index = 0
            let bool = false
            that.outputFileTypeArray.forEach((val, key) => {
              if (val.activityId === that.activityId) {
                bool = true
                index = key
              }
            })

            if (bool) {
              that.outputFileTypeArray.splice(index, 1, properties)
            } else {
              that.outputFileTypeArray.push(properties)
            }
            this.$emit('outputFileType', that.outputFileTypeArray)
          }*/


    }
  }
</script>

<style lang="scss" scoped>
  .property-panel {
    position: absolute;
    right: 10px;
    top: 80px;
    padding: 10px 0;
    width: 220px;
    height: 700px;
    background:#ECF4FF ;
  }
  .ant-card-bordered {
    border: 1px solid #ECF4FF;
  }
  .itemm{
    margin:0px;
    padding: 11px 0px 0px 11px;

  }


</style>
